<?php

namespace Plugin\CopyProduct;


use Beike\Admin\Http\Resources\ProductAttributeResource;
use Beike\Admin\Http\Resources\ProductResource;
use Beike\Models\Product;
use Beike\Repositories\CategoryRepo;
use Beike\Repositories\LanguageRepo;
use function Symfony\Component\HttpFoundation\getDomain;
use function Termwind\ValueObjects\pr;

class Bootstrap
{
    public function boot()
    {

        //复制按钮
        add_hook_blade('admin.product.list.action', function ($callback, $output, $data) {
            $copy_url = admin_route("products.create", []);
            $view     = view('CopyProduct::admin.copy_btn', ['copy_url' => $copy_url])->render();
            return $output . $view;
        });


        //拦截进入创建界面的数据
        add_hook_filter('admin.product.form.data', function ($data) {
            //print_r(json_encode($data['product']));
            $copy_id = request()->copy_id ? request()->copy_id : 0;
            if ($copy_id > 0) {
                $pid          = $data['product']->id ? $data['product']->id : 0;
                $product      = Product::query()->where('id', $copy_id)->first();
                $descriptions = $product->descriptions->keyBy('locale');
                $categoryIds  = $product->categories->pluck('id')->toArray();
                $product->load('brand', 'attributes');


                $data['descriptions']       = $descriptions ?? [];
                $data['category_ids']       = $categoryIds ?? [];
                $data['product_attributes'] = ProductAttributeResource::collection($product->attributes);
                $data['relations']          = ProductResource::collection($product->relations)->resource;

                if ($pid == 0) {
                    // unset($product->id);
                }
                $data['product'] = $product;
            }
            return $data;
        });


        //调整创建界面里的提交方式和地址
        add_hook_blade("admin.product.edit.brand", function ($callback, $output, $data) {
            $copy_id = request()->copy_id ? request()->copy_id : 0;
            if ($copy_id > 0) {
                $post_url = admin_route("products.store", []);
                $view     = view('CopyProduct::admin.update_method', ['post_url' => $post_url])->render();
                return $output . $view;
            }
            return $output;
        });

    }
}
